import { _decorator, Component, Node, Vec3, Vec2, toDegree } from 'cc';
import { BulletConfig } from './BulletConfig';
import { Enemy } from './Enemy';
import { GameManager } from './GameManager';
const { ccclass, property } = _decorator;

@ccclass('Bullet')
export class Bullet extends Component
{

    public static BULLET_DAMAGE = 1
    public Config: BulletConfig

    private curPos: Vec3 = new Vec3()

    start()
    {
        this.node.setPosition(this.Config.v2InitPos.x, this.Config.v2InitPos.y)
        if (Vec2.cross(this.Config.v2Dir,new Vec2(1,1).normalize()) > 0) {
            this.node.angle = -toDegree(Vec2.angle(this.Config.v2Dir,new Vec2(1,1).normalize()))
        }
        else
        {
            this.node.angle = toDegree(Vec2.angle(this.Config.v2Dir,new Vec2(1,1).normalize()))
        }
    }

    update(deltaTime: number)
    {
        if (GameManager.instance.IsGamePause > 0) {
            return
        }
        this.Config.nLiveTime -= deltaTime
        if (this.Config.nLiveTime <= 0)
        {
            this.node.destroy()
        }

        this.node.getPosition(this.curPos)
        this.curPos.x = this.curPos.x + this.Config.v2Dir.x * this.Config.nMoveSpeed
        this.curPos.y = this.curPos.y + this.Config.v2Dir.y * this.Config.nMoveSpeed
        this.node.setPosition(this.curPos)

        let e = GameManager.instance.CheckHit(this.curPos)
        if (e != null)
        {
            let s = e.getComponent(Enemy)
            s.Hurt(Bullet.BULLET_DAMAGE, GameManager.instance.Player)
            s.HitBack(100, this.Config.Source)
            this.node.destroy() // todo 内存池优化
        }
    }
}


